package wechat

import (
	"crypto/sha1"
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/rffanlab/goutils/requests"

	"io"
	"sort"
	"strings"
)

// Verify 微信验证签名接口
func (c *Wechat) Verify(signature, timestamp, nonce, echostr string) (respStr string) {
	sl := []string{c.Token, timestamp, nonce}
	sort.Strings(sl)
	s := sha1.New()
	_, err := io.WriteString(s, strings.Join(sl, ""))
	if err != nil {
		return ""
	}
	sign := fmt.Sprintf("%x", s.Sum(nil))
	if signature == sign {
		return echostr
	}
	return
}

func (c *Wechat) GetAccessToken() (accessToken string, err error) {
	r := requests.Requests{}
	r.AddParams("grant_type", "client_credential")
	r.AddParams("appid", c.Appid)
	r.AddParams("secret", c.AppSecret)
	if result, err := r.Get("https://api.weixin.qq.com/cgi-bin/token"); err == nil {
		wxResp := WechatAccessTokenResp{}
		err := json.Unmarshal([]byte(result), &wxResp)
		if err != nil {
			return "", err
		}
		if wxResp.AccessToken != "" {
			accessToken = wxResp.AccessToken
			c.AccessToken = accessToken
		} else {
			fmt.Println(result)
			err = errors.New(wxResp.Errmsg)
		}
	}
	return
}
